<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>智慧农业管理系统</h2>
        <p>请登录您的账户</p>
      </div>
      
      <form @submit.prevent="handleLogin" class="login-form">
        <div class="form-group">
          <label for="username">用户名</label>
          <input
            id="username"
            v-model="loginForm.username"
            type="text"
            placeholder="请输入用户名"
            required
            :disabled="loading"
          />
        </div>
        
        <div class="form-group">
          <label for="password">密码</label>
          <input
            id="password"
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            required
            :disabled="loading"
          />
        </div>
        
        <div class="form-group">
          <label class="checkbox-label">
            <input
              v-model="loginForm.remember"
              type="checkbox"
              :disabled="loading"
            />
            <span>记住我</span>
          </label>
        </div>
        
        <button
          type="submit"
          class="login-btn"
          :disabled="loading"
        >
          {{ loading ? '登录中...' : '登录' }}
        </button>
      </form>
      
      <div v-if="errorMessage" class="error-message">
        {{ errorMessage }}
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { api } from '../utis/request'
import toast from '../utils/toast'

const router = useRouter()
const loading = ref(false)
const errorMessage = ref('')

const loginForm = reactive({
  username: '',
  password: '',
  remember: false
})

const handleLogin = async () => {
  if (!loginForm.username || !loginForm.password) {
    errorMessage.value = '请输入用户名和密码'
    return
  }
  
  loading.value = true
  errorMessage.value = ''
  
  try {
    const response = await api.user.login({
      username: loginForm.username,
      password: loginForm.password
    })
    
    // 根据新的API响应格式，用户信息直接在data中
    const userInfo = response.data
    
    // 保存用户信息到localStorage（这里可以根据需要生成一个简单的token）
    // 使用 encodeURIComponent 和 btoa 来安全地编码包含中文的JSON字符串
    const userInfoStr = JSON.stringify(userInfo)
    const token = btoa(encodeURIComponent(userInfoStr)) // 安全的base64编码作为临时token
    localStorage.setItem('token', token)
    
    // 如果选择记住我，保存用户信息
    if (loginForm.remember) {
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    }
    
    // 显示登录成功提示
    toast.success('登录成功', `欢迎回来，${userInfo.realName || userInfo.username}！`)
    
    // 跳转到首页
    router.push('/home')
    
  } catch (error: any) {
    console.error('登录错误:', error)
    
    // 更详细的错误处理
    if (error.code === 'ERR_NETWORK') {
      errorMessage.value = '网络连接失败，请检查后端服务是否启动'
    } else if (error.response?.status === 401) {
      errorMessage.value = '用户名或密码错误'
    } else if (error.response?.status === 405) {
      errorMessage.value = '请求方法不允许，请检查API配置'
    } else if (error.response?.status >= 500) {
      errorMessage.value = '服务器内部错误，请稍后重试'
    } else {
      errorMessage.value = error.message || '登录失败，请检查用户名和密码'
    }
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.login-box {
  background: white;
  border-radius: 12px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  padding: 40px;
  width: 100%;
  max-width: 400px;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  color: #333;
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
}

.login-header p {
  color: #666;
  margin: 0;
  font-size: 14px;
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.form-group input[type="text"],
.form-group input[type="password"] {
  padding: 12px 16px;
  border: 2px solid #e1e5e9;
  border-radius: 8px;
  font-size: 14px;
  transition: border-color 0.3s ease;
}

.form-group input[type="text"]:focus,
.form-group input[type="password"]:focus {
  outline: none;
  border-color: #667eea;
}

.form-group input:disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  font-size: 14px;
  color: #666;
}

.checkbox-label input[type="checkbox"] {
  width: 16px;
  height: 16px;
  cursor: pointer;
}

.login-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 14px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.login-btn:hover:not(:disabled) {
  transform: translateY(-2px);
}

.login-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

.error-message {
  margin-top: 16px;
  padding: 12px;
  background-color: #fee;
  border: 1px solid #fcc;
  border-radius: 6px;
  color: #c33;
  font-size: 14px;
  text-align: center;
}
</style> 